<script setup>
import { reactive, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { getUsername } from "@/router/user";
import { Message } from "@arco-design/web-vue";
import { CREATEBLOG, DETAILBLOG, UPDATEBLOG } from "@/api/post";
import Cookies from "js-cookie";
import MdEditor from "md-editor-v3";
import "md-editor-v3/lib/style.css";

const form = reactive({
  title: "",
  content: "",
  summary: "",
  isRead: false,
});
let title = ref("");
let id = ref(0);
const loading = ref(false);
const router = useRouter();
let oldBlog = {};
onMounted(async () => {
  if (router.currentRoute.value.name === "blogcreate") {
    title.value = "创建博客";
    let params = history.state.params;
    if (params !== undefined) {
      form.title = params.title;
      form.content = params.content;
      form.summary = params.summary;
      form.isRead = params.isRead;
    }
  } else if (router.currentRoute.value.name === "blogUpdate") {
    title.value = "编辑博客";
    if (
      router.currentRoute.value.params.id &&
      router.currentRoute.value.params.id != 0
    ) {
      id.value = router.currentRoute.value.params.id;
      try {
        await DETAILBLOG(router.currentRoute.value.params.id).then(
          (value) => {
            console.log(value.Msg);
            oldBlog = value.Msg;
            form.title = value.Msg.title;
            form.content = value.Msg.content;
            form.summary = value.Msg.summary;
            if (value.Msg.status == "published") {
              form.isRead = true;
            } else {
              form.isRead = false;
            }
          },
          (reason) => {
            console.log(reason);
            router.back();
          }
        );
      } catch (error) {
        console.log(error);
      }
    } else {
      Message.error("访问有误！");
      router.back();
    }
  }
  setInterval(() => {
    history.state["params"] = {
      title: form.title,
      content: form.content,
      summary: form.summary,
      isRead: form.isRead,
    };
  }, 500);
});
const goToList = () => {
  router.push({
    name: "backstageBlogs",
  });
};
const handleSubmit = async ({ values, errors }) => {
  if (errors === undefined) {
    if (getUsername() === undefined) {
      Message.error("未登录");
      // console.log(router, "创建博客页面", form);
      let params = {
        title: form.title,
        content: form.content,
        summary: form.summary,
        isRead: form.isRead,
      };
      router.push({
        name: "login",
        query: {
          rewrite: router.currentRoute.value.path,
          ...router.currentRoute.value.query,
        },
        state: { params: params },
      });
    }
    let status = false;
    if (oldBlog.status === "published") {
      status = true;
    }
    if (
      form.title === oldBlog.title &&
      oldBlog.content === form.content &&
      oldBlog.summary === form.summary &&
      status === form.isRead
    ) {
      Message.warning("未改动");
      router.back();
      return;
    }
    loading.value = true;
    const body = {
      title: form.title,
      content: form.content,
      summary: form.summary,
      author: getUsername(),
      status: "draft",
    };
    if (values.isRead) {
      body.status = "published";
    }
    // console.log(body);
    try {
      if (router.currentRoute.value.name === "blogcreate") {
        await CREATEBLOG(body).then(
          (value) => {
            // console.log(value);
            history.state["params"] = {};
            if (value.Code === 200) {
              Message.success("发布成功");
              router.push({
                name: "backstageBlogs",
              });
            }
          },
          (reason) => {
            console.log(reason);
            if (reason.indexOf("Duplicate entry") !== -1) {
              Message.error("标题重复");
            } else if (reason.indexOf("Network Error") !== -1) {
              Message.error("后台网络异常");
            } else if (reason === "认证失败") {
              Message.error("尚未登录");
              Cookies.remove("user");
              Cookies.remove("uid");
              let params = {
                title: form.title,
                content: form.content,
                summary: form.summary,
                isRead: form.isRead,
              };
              router.push({
                name: "login",
                query: {
                  rewrite: router.currentRoute.value.path,
                  ...router.currentRoute.value.query,
                },
                state: { params: params },
              });
            } else {
              Message.error(reason);
            }
          }
        );
      } else if (router.currentRoute.value.name === "blogUpdate") {
        await UPDATEBLOG(id.value, body).then(
          (value) => {
            console.log(value);
            history.state["params"] = {};
            if (value.Code === 200) {
              Message.success("更新成功");
              router.push({
                name: "backstageBlogs",
              });
            }
          },
          (reason) => {
            console.log(reason);
            if (reason.indexOf("Duplicate entry") !== -1) {
              Message.error("标题重复");
            } else if (reason.indexOf("Network Error") !== -1) {
              Message.error("后台网络异常");
            } else if (reason === "认证失败") {
              Message.error("尚未登录");
              Cookies.remove("user");
              Cookies.remove("uid");
              let params = {
                title: form.title,
                content: form.content,
                summary: form.summary,
                isRead: form.isRead,
              };
              router.push({
                name: "login",
                query: {
                  rewrite: router.currentRoute.value.path,
                  ...router.currentRoute.value.query,
                },
                state: { params: params },
              });
            } else {
              Message.error(reason);
            }
          }
        );
      }
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
    }
  }
};
</script>
<template>
  <div class="blogslist-fullpage">
    <!-- 头 -->
    <div class="blogslist-hander">
      <div class="blogslist-hander-left">
        <a-breadcrumb :style="{ fontSize: `18px` }">
          <a-breadcrumb-item>
            <a>
              <icon-home :size="24" @click="goToList" />
            </a>
          </a-breadcrumb-item>
          <a-breadcrumb-item>{{ title }}</a-breadcrumb-item>
        </a-breadcrumb>
      </div>
    </div>
    <!-- 编辑部分 -->
    <div class="blogslist-context">
      <a-form
        ref="formRef"
        :model="form"
        layout="vertical"
        @submit="handleSubmit"
      >
        <a-form-item
          field="title"
          label="标题"
          :rules="[
            { required: true, message: '标题不能为空' },
            { minLength: 1, message: '标题不能少于一个字' },
          ]"
        >
          <a-input v-model="form.title" placeholder="请输入标题..." />
        </a-form-item>
        <a-form-item field="summary" label="摘要">
          <a-input v-model="form.summary" placeholder="请输入摘要..." />
        </a-form-item>
        <a-form-item field="content" label="内容">
          <!-- <a-textarea
            placeholder="请输入正文..."
            v-model=""
            allow-clear
            show-word-limit
            :auto-size="{ minRows: 15 }"
          /> -->
          <md-editor v-model="form.content" style="text-align: left" />
        </a-form-item>
        <a-form-item field="isRead">
          <a-checkbox v-model="form.isRead">发布</a-checkbox><br />
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            size="large"
            html-type="submit"
            :loading="loading"
            >提交</a-button
          >
          <a-button @click="$refs.formRef.resetFields()">清空</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<style scoped>
.blogslist-fullpage {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
.blogslist-hander {
  display: flex;
  height: 80px;
  padding: 1% 0;
  flex-direction: column;
  align-items: flex-start;
}
.blogslist-context {
  display: flex;
  height: 100%;
  flex-direction: column;
}
.arco-form-item {
  margin-bottom: auto;
}
</style>
